Naming
For:
- Variables
- Everything else
Never use:
- Hungarian notation
- Putting types before variable names, such as u8_var
- Commonly used because some languages used to have a low amount of types or none (such as BCPL)
- This shouldn't be used it's useless, as python has type hinting.
❌Wrong
def u8Sum(u8A, u8B):
return u8A + u8B
This code uses Hungarian notation.
✅Correct
def sum(a: int, b: int) -> int:
return a + b
This code uses Python's type hints.
- Unintuitive and single letter names
- Python is not math
- Variable names should explain what they do if possible
❌Wrong
def something(a, b, c):
i = 1
n1 = a
n2 = b
r = [n1, n2]
while i < c - 1:
r.append(r[i] + r[i-1])
i = i + 1
return r
something(1, 3, 20)
The variables have single letter names, with no explanation to what they are.
❌Wrong
def something(a, b, c): # fibbonaci-sequence, a is n1, b is n2, c is count
i = 1 # index
n1 = a # number 1 (1 for fib or lucas)
n2 = b # number 2 (1 for fib 3 for lucas)
r = [n1, n2] # First two numbers
while i < c - 1: # repeat while index is under count - 1
r.append(r[i] + r[i-1]) # add sum of list[index] and list[index + 1]
i = i + 1 # update index
return r # return list
something(1, 3, 20) # Lucas' numbers up to L20
And adding comments doesn't make it much better, when you can just name the variables something more readable. Also this adds clutter.
✅Correct
def fibbonaci(number1: int, number2: int, count: int):
index = 1
numbers = [number1, number2]
while index < count - 1:
numbers.append(numbers[index] + numbers[index - 1])
index += 1
return numbers
fibbonaci(1, 3, 20) # Lucas sequence up until L(20)
fibonacci(1, 1, 20) # Fibonacci sequence up until F(20)
This code has readable variable and function names, which could be understood by most people without comments.
Index can be i, however index is preferred.